<?php

namespace app\controller;
use app\BaseController;
use app\model\UserModel;
use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\Request;
use thans\jwt\facade\JWTAuth;

class Login extends BaseController
{
    //登录
    public function userLogin() {
//        print_r(234);die;
        if (!Request::isPost()) {
            return $this->errorPut('请先登录');
        }
        $getData = Request::only(['username','captcha','password'],'post');

        try {
            // 验证前台提交数据的合法性
            $this->Validate($getData,
                [
                    "captcha|验证码" => 'require',
                    "username|用户名" => 'require|max:10',
                    "password|密码" => 'require|max:12',
                ]
            );
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return  $this->errorPut($e->getMessage());
        }


        $getData['password'] = md5(md5($getData['password']));
//        // 检测输入的验证码是否正确，$value为用户输入的验证码字符串
//        if (!captcha_check($getData['captcha'])) {
//            // 验证失败
//            return $this -> errorPut('验证码输入有误');
//        }
        unset($getData['captcha']);

        $model    =  new UserModel();
        $modelOne = $model->getOne($getData);

        if (empty($modelOne)) {
            return $this->errorPut('用户名或者密码错误请重新输入');exit;
        }


        //生成token
        $data = [
            'admin_id'   => $modelOne->user_id,
            'admin_name' => $getData['username'],
            'password'   => $getData['password'],
//            'remember'   => $params['remember'] ?? '0',
        ];
        $token = JWTAuth::builder($data);//参数为用户认证的信息，请自行添加
        $handler = Cache::handler();
        $handler->Rpush('token:'.$modelOne['username'],$token);
        return $this->outPut('登录成功', ['czconfigtoken' => $token,'user'=>$modelOne]);
    }
}
